//
//  BN_SchoolNoticeCell.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-6-17.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#define OBJECT_SPACE 5
#import <QuartzCore/QuartzCore.h>
#import "BN_SchoolNoticeCell.h"
#import "BN_NoticeHelper.h"

@implementation BN_SchoolNoticeCell {
    BN_NoticeHelper *noticeHelper_;
    BN_UserInfo *userInfo_;
}

- (void)awakeFromNib
{
    // UI
    self.contentView.backgroundColor = [UIColor whiteColor];
    self.lineLabel.alpha = 0.4;
    self.createTimeLabel.textColor = [UIColor grayColor];
    self.backgroundColor = [UIColor whiteColor];
    self.replView.backgroundColor = [UIColor clearColor];
    self.contentTextLabel.backgroundColor = [UIColor clearColor];
    self.titleTextLabel.backgroundColor = [UIColor clearColor];
    self.discLikeFenxiangView.backgroundColor = [UIColor clearColor];
    self.dividerView.backgroundColor = APP_OBJECT_GRAY_COLOR;
    self.disPlayImageView.backgroundColor = APP_OBJECT_GRAY_COLOR;
        self.titleTextLabel.frame = CGRectZero;
    self.discLikeFenxiangView.frame = CGRectZero;
    self.contentTextLabel.frame = CGRectZero;
    self.disPlayImageView.frame = CGRectZero;
    self.replView.frame = CGRectZero;
    
    self.disPlayImageView.userInteractionEnabled = YES;
    [self.pinglunBtn addTarget:self action:@selector(pinglunAction) forControlEvents:UIControlEventTouchUpInside];
    [self.fenxiangBtn addTarget:self action:@selector(fenxiangAction) forControlEvents:UIControlEventTouchUpInside];
    if (!noticeHelper_) {
        noticeHelper_ = [[BN_NoticeHelper alloc]init];
    }
    if (!userInfo_) {
        userInfo_ = [BN_UserHelper unArchiverAccountInfo];
    }
    if (!_userType) {
        _userType = [userInfo_.userType integerValue];
    }
}

- (void)contentTextToGroupView:(NSArray *)array {
    // 发布时间
    [_createTimeLabel sizeToFit];
    _createTimeLabel.textAlignment = NSTextAlignmentRight;
    _createTimeLabel.frame = CGRectMake(310-CGRectGetWidth(_createTimeLabel.frame), (42-CGRectGetHeight(_createTimeLabel.frame))/2, CGRectGetWidth(_createTimeLabel.frame), CGRectGetHeight(_createTimeLabel.frame));
    
    // 发布时间小图片
    _createTimeImageView.frame = CGRectMake(CGRectGetMinX(_createTimeLabel.frame)-20, (44-23)/2, 23, 23);
    
    self.titleTextLabel.numberOfLines = 0;
    UIFont *titleLabelfont = [UIFont fontWithName:@"TrebuchetMS-Bold" size:APP_CONTENT_FONT_SIZE];
    self.titleTextLabel.font = titleLabelfont;
    self.titleTextLabel.lineBreakMode = NSLineBreakByCharWrapping ;
    CGSize titleLabelsize = CGSizeMake(300,10000);
    NSDictionary * titleLabeldic = [NSDictionary dictionaryWithObjectsAndKeys:titleLabelfont,NSFontAttributeName,nil];
    CGSize titleLabelActualsize = [self getTextSize:titleLabelsize disFont:titleLabelfont contentStr:self.titleTextLabel.text contextDic:titleLabeldic];
    if (self.titleTextLabel.text.length > 0) {
        self.titleTextLabel.frame = CGRectMake(10, CGRectGetMaxY(self.lineLabel.frame)+OBJECT_SPACE, 300, titleLabelActualsize.height);
    }else {
        self.titleTextLabel.frame = CGRectMake(10, CGRectGetMaxY(self.lineLabel.frame)+OBJECT_SPACE, 300, 0);
    }
    
    // 文字内容
    self.contentTextLabel.numberOfLines = 0;
    UIFont *contLabelfont = [UIFont systemFontOfSize:APP_CONTENT_FONT_SIZE];
    self.contentTextLabel.font = contLabelfont;
    self.contentTextLabel.lineBreakMode = NSLineBreakByCharWrapping ;
    CGSize contLabelsize = CGSizeMake(300,10000);
    NSDictionary * contLabeldic = [NSDictionary dictionaryWithObjectsAndKeys:contLabelfont,NSFontAttributeName,nil];
    CGSize contLabelActualsize = [self getTextSize:contLabelsize disFont:contLabelfont contentStr:self.contentTextLabel.text contextDic:contLabeldic];
    if (![self.contentTextLabel.text isEqualToString:@""]) {
        if ([self.titleTextLabel.text isEqualToString:@""]) {
            self.contentTextLabel.frame = CGRectMake(10, CGRectGetMaxY(self.lineLabel.frame)+OBJECT_SPACE, 300, contLabelActualsize.height);
        }else {
            self.contentTextLabel.frame = CGRectMake(10, CGRectGetMaxY(self.titleTextLabel.frame)+OBJECT_SPACE, 300, contLabelActualsize.height);
        }
    }else {
        self.contentTextLabel.frame = CGRectMake(10, CGRectGetMaxY(self.titleTextLabel.frame), 300, 0);
    }
    
    if (array.count != 0) {
        // 缩略图地址
        NSDictionary *imgDic = array[0];
        NSString *imgURLString = [THUMBNAIL_BASEURL stringByAppendingString:imgDic[@"fileTUrl"]];
        // 从网络上获取图片数据
        self.imageUrl = [NSURL URLWithString:imgURLString];
        [self.disPlayImageView setImageWithURL:self.imageUrl placeholderImage:nil];
        self.disPlayImageView.frame = CGRectMake(10, CGRectGetMaxY(self.contentTextLabel.frame)+OBJECT_SPACE, 150, 150);
        self.disPlayImageView.clipsToBounds = YES;
        self.disPlayImageView.contentMode = UIViewContentModeScaleAspectFill;
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openFullImageViewAction:)];
        [self.disPlayImageView addGestureRecognizer:tapGesture];
    }else {
        self.disPlayImageView.frame = CGRectMake(10, CGRectGetMaxY(self.contentTextLabel.frame), 150, 0);
    }

    // 评论、点赞、分享按钮
    self.discLikeFenxiangView.frame = CGRectMake(0, CGRectGetMaxY(self.disPlayImageView.frame)+OBJECT_SPACE, SCREEN_WIDTH, 36);
    
    // 回复视图
    self.replView.frame = CGRectMake(0, CGRectGetMaxY(self.discLikeFenxiangView.frame)+OBJECT_SPACE, SCREEN_WIDTH, [self dealreplView]);
    
    // 分割线
    self.dividerView.frame = CGRectMake(0, CGRectGetMaxY(self.replView.frame)+OBJECT_SPACE, SCREEN_WIDTH, 15);
    
    self.cellHeight = CGRectGetMaxY(self.dividerView.frame)+OBJECT_SPACE;
}

- (void)dealLikeBtnColorState {
    self.xihuanBtn.transform = CGAffineTransformMakeScale(1.0, 1.0);
    self.xihuanBtn.enabled = YES;
    NSInteger praiTime = [self.praiTime integerValue];
    if (praiTime > 0) {
        [self.xihuanBtn setImage:[UIImage imageNamed:@"dianjixihuan"] forState:UIControlStateNormal];
    }else {
        [self.xihuanBtn setImage:[UIImage imageNamed:@"xihuan"] forState:UIControlStateNormal];
    }
    [self.xihuanBtn addTarget:self action:@selector(xihuanAction) forControlEvents:UIControlEventTouchUpInside];
}

- (CGFloat)dealreplView {
    
    // 评论数要求3行显示.大于3=条评论，第一行显示查看更多，2、3行显示最新2条评论
    if (self.replTime >= 3) {
        
        self.singleRelpHeight = 23;
        self.replTime = 2;
        
        for (int i = 0; i < 3; i++) {
            if (i == 0) {
                UIButton *allPinglunBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                allPinglunBtn.frame = CGRectMake(12, 0, 100, 20);
                [allPinglunBtn addTarget:self action:@selector(toViewPinglunVC) forControlEvents:UIControlEventTouchUpInside];
                allPinglunBtn.titleEdgeInsets =  UIEdgeInsetsMake(0 ,-15, 0, 0);
                [allPinglunBtn setTitle:@"查看全部评论" forState:UIControlStateNormal];
                allPinglunBtn.titleLabel.font = [UIFont systemFontOfSize:14];
                [allPinglunBtn setTitleColor:APP_OBJECT_GREEN_COLOR forState:UIControlStateNormal];
                [self.replView addSubview:allPinglunBtn];
            }else {
                // replUserName replCont
                NSString *name = self.replArr[i-1][@"replUserName"];
                NSString *content = self.replArr[i-1][@"replCont"];
                // replName
                UILabel *replNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(12, self.singleRelpHeight, 0, 20)];
                replNameLabel.text = [name stringByAppendingString:@" : "];
                replNameLabel.backgroundColor = [UIColor clearColor];
                replNameLabel.textColor = APP_OBJECT_GREEN_COLOR;
                replNameLabel.tag = 10+i;
                replNameLabel.font = [UIFont systemFontOfSize:14.0f];
                [self.replView addSubview:replNameLabel];
                [replNameLabel sizeToFit];
                
                // replContent
                UILabel *replCountLabel = [[UILabel alloc]init];
                replCountLabel.text = content;
                replCountLabel.backgroundColor = [UIColor clearColor];
                replCountLabel.tag = 20+i;
                replCountLabel.numberOfLines = 0;
                UIFont *contLabelfont = [UIFont systemFontOfSize:14];
                replCountLabel.font = contLabelfont;
                replCountLabel.lineBreakMode = NSLineBreakByCharWrapping ;
                CGSize contLabelsize = CGSizeMake(SCREEN_WIDTH-12*2-(CGRectGetWidth(replNameLabel.frame)),10000);
                NSDictionary * contLabeldic = [NSDictionary dictionaryWithObjectsAndKeys:contLabelfont,NSFontAttributeName,nil];
                CGSize contLabelActualsize = [self getTextSize:contLabelsize disFont:contLabelfont contentStr:replCountLabel.text contextDic:contLabeldic];
                replCountLabel.frame = CGRectMake(CGRectGetMaxX(replNameLabel.frame), self.singleRelpHeight, SCREEN_WIDTH-12*2-(CGRectGetWidth(replNameLabel.frame)), contLabelActualsize.height);
                [self.replView addSubview:replCountLabel];
                
                self.singleRelpHeight = CGRectGetMaxY(replCountLabel.frame)+OBJECT_SPACE;
                self.relpHeight = CGRectGetMaxY(replCountLabel.frame)+10.0f;
            }
        }
    }else {
        self.singleRelpHeight = 0;
        for (int i = 0; i < self.replTime; i++) {
            // replUserName replCont
            NSString *name = self.replArr[i][@"replUserName"];
            NSString *content = self.replArr[i][@"replCont"];
            
            // replName
            UILabel *replNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(12, self.singleRelpHeight, 0, 20)];
            replNameLabel.text = [name stringByAppendingString:@" : "];
            replNameLabel.backgroundColor = [UIColor clearColor];
            replNameLabel.textColor = APP_OBJECT_GREEN_COLOR;
            replNameLabel.font = [UIFont systemFontOfSize:14.0f];
            [self.replView addSubview:replNameLabel];
            [replNameLabel sizeToFit];
            
            // replContent
            UILabel *replCountLabel = [[UILabel alloc]init];
            replCountLabel.text = content;
            replCountLabel.backgroundColor = [UIColor clearColor];
            
            replCountLabel.numberOfLines = 0;
            UIFont *contLabelfont = [UIFont systemFontOfSize:14];
            replCountLabel.font = contLabelfont;
            replCountLabel.lineBreakMode = NSLineBreakByCharWrapping ;
            CGSize contLabelsize = CGSizeMake(SCREEN_WIDTH-12*2-(CGRectGetWidth(replNameLabel.frame)),10000);
            NSDictionary * contLabeldic = [NSDictionary dictionaryWithObjectsAndKeys:contLabelfont,NSFontAttributeName,nil];
            CGSize contLabelActualsize = [self getTextSize:contLabelsize disFont:contLabelfont contentStr:replCountLabel.text contextDic:contLabeldic];
            replCountLabel.frame = CGRectMake(CGRectGetMaxX(replNameLabel.frame), self.singleRelpHeight, SCREEN_WIDTH-12*2-(CGRectGetWidth(replNameLabel.frame)), contLabelActualsize.height);
            [self.replView addSubview:replCountLabel];
            self.singleRelpHeight = CGRectGetMaxY(replCountLabel.frame)+OBJECT_SPACE;
            self.relpHeight = CGRectGetMaxY(replCountLabel.frame)+10.0f;
        }
    }
    return self.relpHeight;
}

#pragma mark
#pragma mark Actions 
- (void)xihuanAction {
    __weak typeof (self) weakSelf = self;
    // 判断接口中praiFlg的值，如果为0表示未赞，其值改为1。为其他值的时候，其值为0
    self.xihuanBtn.enabled = NO;
    [self likeAnimation:self.xihuanBtn];
    [noticeHelper_ supportNoticeWithId:self.notiId flg:self.praiFlg completeHandler:^(id result, NSString *errMsg) {
        if (errMsg) {
            weakSelf.xihuanBtn.enabled = YES;
            // 网络请求成功后，更改model中网络数组
            // praiFlg
            switch (self.praiFlg) {
                case 0:
                    self.praiFlg = 1;
                    break;
                case 1:
                    self.praiFlg = 0;
                    break;
                default:
                    break;
            }
            NSString *tag_ = [NSString stringWithFormat:@"%ld",(long)self.tag];
            NSString *praiFlg_ = [NSString stringWithFormat:@"%ld",(long)self.praiFlg];
            NSArray *sendArr = @[tag_,praiFlg_];
            [[NSNotificationCenter defaultCenter]postNotificationName:K_NOTICE_LIKE_NETARRAY_VALUE object:sendArr];
        }else{
            weakSelf.xihuanBtn.enabled = YES;
            [LZCHINT title:errMsg type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
        }
    }];
}

- (void)pinglunAction {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setBool:YES forKey:@"USERDEFAULTS_PINGLUN_TYPE"];
    [userDefaults synchronize];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"KNOTICE_PUSHPINLUNVC"  object:self.notiId];
}

- (void)fenxiangAction {
    NSArray *itemNameArr = nil;
    switch (_userType) {
        case ENUM_ROLE_LEADER:
        {
            itemNameArr = @[@"删除通知",@"举报此通知"];
        }
            break; // 园长
        case ENUM_ROLE_CLASS_TEACHER:
        {
            itemNameArr = @[@"删除通知",@"举报此通知"];
        }
            break; // 班级老师
            
        case ENUM_ROLE_PARENT:
        {
            itemNameArr = @[@"收藏通知",@"举报此通知"];
        }
            break; // 家长
        default:
            break;
    }
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil
                                                            delegate:self
                                                   cancelButtonTitle:@"取消"
                                              destructiveButtonTitle:nil
                                                   otherButtonTitles:itemNameArr[0],itemNameArr[1],nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    [actionSheet showInView:self.contentView];
}

- (void)parentShareAction {
    switch (self.favoFlg) {
        case 0:
            [noticeHelper_ collectNoticeWithId:self.notiId completeHandler:^(id result, NSString *errMsg) {
                if (errMsg) {
                    [LZCHINT title:@"已转到我的主页" type:LZCSuccess duration:2 places:HINT_PLACES callBack:NULL];
                    [[NSNotificationCenter defaultCenter]postNotificationName:K_NOTICE_SHARE_NETARRAY_VALUE object:nil];
                }else{
                    [LZCHINT title:@"收藏失败" type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
                }
            }];
            break;
        case 1:
            [LZCHINT title:@"已收藏" type:LZCInfo duration:2 places:HINT_PLACES callBack:NULL];
            break;
        default:
            break;
    }
}

- (void)deleteAction {
    UIAlertView *deleAlrtView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"是否删除此条通知?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    deleAlrtView.tag = 201;
    [deleAlrtView show];
}

- (void)toViewPinglunVC {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setBool:NO forKey:@"USERDEFAULTS_PINGLUN_TYPE"];
    [userDefaults synchronize];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"KNOTICE_PUSHPINLUNVC"  object:self.notiId];
}

- (void)openFullImageViewAction:(UITapGestureRecognizer *)tap {
    NSMutableArray *photos = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i<1; i++) {
        MJPhoto *photo = [[MJPhoto alloc] init];
        photo.url = self.imageUrl;
        photo.srcImageView = self.disPlayImageView;
        [photos addObject:photo];
    }
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.currentPhotoIndex = tap.view.tag;
    browser.photos = photos;
    [browser show];
}

#pragma mark
#pragma mark 工具
// 封装自动撑开高度的方法
- (CGSize)getTextSize:(CGSize)provisionsSize disFont:(UIFont *)font contentStr:(NSString *)contentStr contextDic:(NSDictionary *)contextDic {
    CGSize size;
    switch (MAIN_VERSION) {
        case 6:
            size = [contentStr sizeWithFont:font constrainedToSize:provisionsSize lineBreakMode:NSLineBreakByWordWrapping];
            break;
        default:
            
            size =[contentStr boundingRectWithSize:provisionsSize options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:contextDic context:nil].size;
            break;
    }
    return size;
}

// 点赞动画
- (void)likeAnimation:(UIView *)zanView {
    [UIView animateWithDuration:0.3 animations:^{
        zanView.transform = CGAffineTransformMakeScale(1.2, 1.2);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 animations:^{
            zanView.transform = CGAffineTransformMakeScale(0.9, 0.9);
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.3 animations:^{
                zanView.transform = CGAffineTransformMakeScale(1.0, 1.0);
            } completion:^(BOOL finished) {
            }];
        }];
    }];
}

#pragma mark
#pragma mark UIAlterView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 201) {
        if (buttonIndex == 1) {
            [noticeHelper_ removeNoticeWithId:self.notiId completeHandler:^(id result, NSString *errMsg) {
                if (errMsg) {
                    [LZCHINT title:@"删除成功" type:LZCError duration:3 places:HINT_PLACES callBack:NULL];
                    [[NSNotificationCenter defaultCenter]postNotificationName:K_NOTICE_DELE_NETARRAY_VALUE object:nil];
                }else{
                    NSLog(@"删除通知的结果:%@",result);
                }
            }];
        }
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:
        {
            if (_userType == ENUM_ROLE_PARENT) {
                [self parentShareAction];
            }else {
                [self deleteAction];
            }
        }
            break; // 家长收藏、其他删除
        case 1:
            [[NSNotificationCenter defaultCenter]postNotificationName:K_REPORT_NOTICE_INFO object:nil];
            break; // 举报
        default:
            break;
    }
}

- (void)willPresentActionSheet:(UIActionSheet *)actionSheet {
    for (UIView *view in actionSheet.subviews) {
        if (view.tag == 2) {
            UIButton *button = (UIButton *) view;
            // 改变背景
            [button setBackgroundImage:[button backgroundImageForState:UIControlStateHighlighted] forState:UIControlStateNormal];
            // 改变颜色
            [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            // btn的选择状态,否则选择后不变背景
            [button setSelected:YES];
        } else {
            // code...
        }
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:K_NOTICE_LIKE_NETARRAY_VALUE object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:K_NOTICE_SHARE_NETARRAY_VALUE object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:K_NOTICE_DELE_NETARRAY_VALUE object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:K_REPORT_INFO object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:K_REPORT_NOTICE_INFO object:nil];

    NSLog(@"新通知CELL 释放了...");
}

@end
